package vn.gq.app4vn.doctruyen;

import org.json.JSONException;
import org.json.JSONObject;
import com.startapp.android.publish.StartAppAd;
import vn.gq.cd.adutils.StartAppHelper;
import vn.gq.cd.model.GooglePlayAdapter;
import vn.gq.cd.model.GooglePlayAdapter.GooglePlayAccount;
import vn.gq.cd.widget.PopupWindow;
import vn.gq.tym.utils.Client;
import vn.gq.tym.utils.DataType;
import vn.gq.tym.utils.DialogHelper;
import vn.gq.tym.utils.GooglePlay;
import vn.gq.tym.utils.IClientListener;
import vn.gq.tym.utils.IDialogHelper;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

public class HomeActivity extends BaseActivity implements OnClickListener {

	private Button btnReading, btnContact, btnGoPlay, btnExit;
	private PopupWindow mPopupWindow;
	private Handler mHandler = new Handler();
	private StartAppAd startAppAd = new StartAppAd(this);
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_home);
		StartAppHelper.showSearchBox(this);
		if (!getString(R.string.author).equals("")) {
			getSupportActionBar().setSubtitle(getString(R.string.author));
		}
		initializePopupWindow();
		btnReading = (Button) findViewById(R.id.btnRead);
		btnReading.setOnClickListener(this);
		btnGoPlay = (Button) findViewById(R.id.btnStore);
		btnGoPlay.setOnClickListener(this);
		btnContact = (Button) findViewById(R.id.btnContact);
		btnContact.setOnClickListener(this);
		btnExit = (Button) findViewById(R.id.btnExit);
		btnExit.setOnClickListener(this);
	}
	
	public void initializePopupWindow() {
		final LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		mPopupWindow = new PopupWindow(this, 300, WindowManager.LayoutParams.WRAP_CONTENT, true, false);
		ViewGroup popupView = (ViewGroup) inflater.inflate(R.layout.popup_choosestore, null, false);
		mPopupWindow.setContentView(popupView);
		ListView listview = (ListView) popupView.findViewById(R.id.list);
		final GooglePlayAdapter adapter = new GooglePlayAdapter(this);
		listview.setAdapter(adapter);
		listview.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				if (id > -1) {
					GooglePlayAccount item = (GooglePlayAccount) adapter.getItem(position);
					GooglePlay.startActivityForPub(HomeActivity.this, item.uri);
				}
			}
		});
	}
	
	public void sendEmail() {
		PackageInfo pkgInfo = null;
		try {
			pkgInfo = getPackageManager().getPackageInfo(getPackageName(), PackageManager.GET_META_DATA);
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		String mEmailBody = String.format("\n\n\n\n\n\n" +
				"-------------------" +
				"\nTên ứng dụng: %s\nMã ứng dụng: %s", getString(R.string.app_name), getPackageName());
		if (pkgInfo != null) {
			mEmailBody += String.format("\nMã phiên bản: %d", pkgInfo.versionCode);
		}
		mEmailBody += "\n-------------------";
		
		Intent intent = new Intent(Intent.ACTION_SEND);
		intent.putExtra(Intent.EXTRA_SUBJECT, "Góp ý, nhận xét, yêu cầu truyện");
		intent.putExtra(Intent.EXTRA_TEXT, mEmailBody);
		intent.putExtra(Intent.EXTRA_EMAIL, new String[] { "ungdungviet.llc@gmail.com" });
		intent.setType("message/rfc822");
		try {
			startActivity(Intent.createChooser(intent, "Chọn ứng dụng gửi mail"));
		} catch(ActivityNotFoundException e) {
			Toast.makeText(this, "Không tìm thấy ứng dụng email trong máy", Toast.LENGTH_SHORT).show();
		}
	}

	@Override
	public void onClick(View v) {
		if (v.equals(btnReading)) {
			Intent intent = new Intent(this, MainActivity.class);
			startActivity(intent);
		} else if (v.equals(btnGoPlay)) {
			final ProgressDialog p = ProgressDialog.show(HomeActivity.this, "", "Loading, plz wait...");
			
			Client c = new Client(getApplicationContext());
			c.setOutputDataType(DataType.JSON);
			c.executeAndListener(String.format("http://apps.cucdinh.vn/android/moreapp?pid=%s&v=%d", getPackageName(), Configuration.CONFIG_MOREAPP_VERSION), new IClientListener() {
				
				@Override
				public void onDone(int code, Object result) {
					p.dismiss();
					if (result != null) {
						JSONObject res = (JSONObject) result;
						try {
							String url = res.getString("url");
							if (url.startsWith("http")) {
								
								Intent intent = new Intent(HomeActivity.this, MoreAppActivity.class);
								intent.putExtra("URL", url);
								startActivity(intent);
								
							} else if (url.startsWith("market:")) {
								GooglePlay.googlePlaySearchPub(HomeActivity.this, url);
							}
							
						} catch (JSONException e) {
							e.printStackTrace();
							Toast.makeText(HomeActivity.this, "Lỗi kết nối, vui lòng thử lại sau !", Toast.LENGTH_SHORT).show();
						}
					}
				}
			});
			
//			mPopupWindow.showAtLocation(btnGoPlay, Gravity.CENTER, 0, 0);
			
		} else if (v.equals(btnContact)) {
			sendEmail();
		} else if (v.equals(btnExit)) {
			onBackPressed();
		}
	}
	
	private AlertDialog dialog;
	
	public void showDialogOnExit() {
		if (dialog == null || ((dialog != null) && !dialog.isShowing())) {
			DialogHelper.showExitDialog(this, "Hãy dành chút thời gian đánh giá cho ứng dụng!", new IDialogHelper() {
				
				@Override
				public void onOk() {
					GooglePlay.startAcitivityForDetail(HomeActivity.this);
				}
				
				@SuppressWarnings("deprecation")
				@Override
				public void onCancel() {
					onDestroy();
					System.runFinalizersOnExit(true);
					System.exit(0);
				}
			});
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		startAppAd.onResume();
	}

	@Override
	public void onBackPressed() {
		
		if (mPopupWindow.isShowing()) {
			mPopupWindow.dismiss();
		} else {
			startAppAd.onBackPressed();
			mHandler.postDelayed(new Runnable() {
				
				@Override
				public void run() {
					showDialogOnExit();
				}
			}, 500);
			
		}
	}

}
